package com.lzq.chatroom_project.controller;

import com.lzq.chatroom_project.common.pojo.Result;
import com.lzq.chatroom_project.common.pojo.ResultCode;
import com.lzq.chatroom_project.common.utils.*;
import com.lzq.chatroom_project.model.User;
import com.lzq.chatroom_project.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.lzq.chatroom_project.common.constants.CacheKeyConstants.ONLINE_USER_INFO_KEY;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private CacheUtil cacheUtil;


    /**
     * 用户登录
     * @param username
     * @param password
     * @param session
     * @return Result(token)
     */
    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        log.info("开始执行login方法, 接收参数:username:{}, password:{}", username, password);
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error("参数不合法, username:{}, password:{}", username, password);
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        User userInfo = userService.getUserByName(username);
        if (userInfo == null || userInfo.getUserId() < 0 || !SecurityUtil.verify(password, userInfo.getPassword())) {
            log.error("用户不存在或密码错误, userInfo:{}", userInfo);
            return Result.failed(ResultCode.FAILED_LOGIN);
        }
        //httpSession中存储user对象
        session.setAttribute("user", userInfo);
        //claims及token的生成
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getUserId());
        claims.put("username", userInfo.getUsername());
        String token = JwtUtil.genJwt(claims);
        log.info("生成token:{}",token);
        return Result.success(token);
    }

    /**
     * 用户注册
     * @param username
     * @param nickname
     * @param password
     * @param repeatedPassword
     * @return Result(true)
     */
    @PostMapping("/registry")
    public Result registry(String username,String nickname,String password,String repeatedPassword) {
        log.info("开始执行registry方法,接收参数:username:{},nickname:{},password:{}",username,nickname,password);
        if (!StringUtils.hasLength(username)
                || !StringUtils.hasLength(nickname)
                || !StringUtils.hasLength(password)
                || !StringUtils.hasLength(repeatedPassword)) {
            log.error("参数不合法,username:{},nickname:{},password:{},repeatedPassword:{}",username,nickname,password,repeatedPassword);
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if (!password.equals(repeatedPassword)) {
            log.error("两次输入的密码不一样,password:{},repeatedPassword:{}",password,repeatedPassword);
            return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //根据username获取user对象,防止用户名冲突
        User user = userService.getUserByName(username);
        if (user != null && user.getUserId() > 0) {
            log.error("用户已存在,user:{}",user);
            return Result.failed(ResultCode.FAILED_USER_EXISTS);
        }
        //user对象的构建及插入user表
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setNickname(nickname);
        String finalPassword = SecurityUtil.encrypt(password);
        newUser.setPassword(finalPassword);
        userService.addUser(newUser);
        return Result.success(true);
    }

    /**
     * 获取用户信息
     * @param request
     * @return Result(user)
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        String jwt = request.getHeader("user_token");
        log.info("开始执行getUserInfo方法");
        Integer userId = (Integer) JwtUtil.getUserIdFromToken(jwt).getData();
        if (userId != null) {
            User userInfo;
            if (cacheUtil.hasKey(ONLINE_USER_INFO_KEY + userId)) {
                userInfo = JacksonUtil.readValue(cacheUtil.get(ONLINE_USER_INFO_KEY + userId), User.class);
            } else {
                userInfo = userService.getUserById(userId);
                cacheUtil.set(ONLINE_USER_INFO_KEY + userId, JacksonUtil.writeValueAsString(userInfo));
            }
            log.info("查询到的用户信息:{}",userInfo);
            return Result.success(userInfo);
        }
        log.error("查询的用户信息不存在");
        return Result.failed(ResultCode.FAILED);
    }

}
